﻿using System;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Linq;
using System.Web;
using Top.Api;
using Top.Api.Domain;
using Top.Api.Request;
using Top.Api.Response;
using DBControl;

namespace KSGJ.AjaxCommand
{
    /// <summary>
    /// setallprice 的摘要说明
    /// </summary>
    public class setallprice : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        private static ITopClient client = new DefaultTopClient(WebConfigurationManager.AppSettings["AppUrl"].ToString(), WebConfigurationManager.AppSettings["AppKey"].ToString(), WebConfigurationManager.AppSettings["AppSecret"].ToString());

        private string errMsg = "";

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string ptitle = context.Request.Form["title"];
            string goodid = context.Request.Form["goodid"];
            string goodprice = context.Request.Form["price"];
            string usersessionkey = context.Session["sessionKey"].ToString();
            string gaijiaovertime = context.Request.Form["overtime"];
            string gaijiastarttime = context.Request.Form["starttime"];
            string type = context.Request.Form["gajiatype"].ToString() == "1" ? "DISCOUNT" : "PRICE";
            SqlDbHelper sdh = new SqlDbHelper();

            List<Promotion> p = new List<Promotion>(); bool parentins = true; Guid parentid = Guid.NewGuid();
            //宝贝总数

            string[] gidlist = goodid.Split(',');
            int goodcount = gidlist.Length;
            string tempid  = "";
            int ti = 1;
            try
            {
                if (goodcount > 10)
                {
                    int tempcount = goodcount % 10;
                    if (tempcount > 0)
                    {
                        for (int i = 0; i < goodcount; i++)
                        {
                            tempid += gidlist[i] + ",";
                            if ((ti % 10) == 0)
                            {
                                string tid = tempid.Substring(0, tempid.Length - 1);
                                addPromotion(ptitle, tid, type, goodprice, usersessionkey, gaijiaovertime, gaijiastarttime, out p);//添加优惠
                                tempid = "";
                            }
                            else if (i == goodcount - 1)
                            {
                                string tid = tempid.Substring(0, tempid.Length - 1);
                                addPromotion(ptitle, tid, type, goodprice, usersessionkey, gaijiaovertime, gaijiastarttime, out p);//添加优惠
                                tempid = "";
                            }
                            if (p.Count > 0)
                            {
                                if (parentins)
                                {
                                    string prentNew = "INSERT INTO Promotionactive(PromotionactiveID,PromotionactiveName,StartDate,EndDate,DiscountType,DiscountValue,Owners)";
                                    prentNew += "VALUES('" + parentid + "','" + ptitle + "','" + gaijiastarttime + "','" + gaijiaovertime + "','" + type + "','" + goodprice + "','" + context.Session["usNick"] + "')";
                                    if (sdh.ExecuteNonQuery(prentNew) > 0)
                                    {
                                        parentins = false;
                                    }

                                }
                                foreach (var item in p)
                                {
                                    ItemGetRequest itemget = new ItemGetRequest();
                                    itemget.Fields = "pic_url,detail_url,price";
                                    itemget.NumIid = item.NumIid;
                                    ItemGetResponse itemresponse = client.Execute(itemget);
                                    string promotionNew = "INSERT INTO Promotion(Pid,Numid,DiscountType,DiscountValue,Startime,Endtime,Promotiontitle,TagID,ParentID,Picurl,Oldprice,Detailurl)";
                                    promotionNew += "VALUES(" + item.PromotionId + "," + item.NumIid + ",'" + type + "','" + goodprice + "','" + gaijiastarttime + "','" + gaijiaovertime + "','" + ptitle + "'," + 1 + ",'" + parentid + "','" + itemresponse.Item.PicUrl + "','" + itemresponse.Item.Price + "','" + itemresponse.Item.DetailUrl + "')";
                                    sdh.ExecuteNonQuery(promotionNew);
                                }
                                p.Clear();
                            }
                            ti++;
                        }
                    }
                }
                else
                {
                    addPromotion(ptitle,goodid, type, goodprice, usersessionkey, gaijiaovertime, gaijiastarttime, out p);//添加优惠
                    if (p.Count > 0)
                    {
                        string prentNew = "INSERT INTO Promotionactive(PromotionactiveID,PromotionactiveName,StartDate,EndDate,DiscountType,DiscountValue,Owners)";
                        prentNew += "VALUES('" + parentid + "','" + ptitle + "','" + gaijiastarttime + "','" + gaijiaovertime + "','" + type + "','" + goodprice + "','" + context.Session["usNick"] + "')";
                        sdh.ExecuteNonQuery(prentNew);
                        foreach (var item in p)
                        {
                            ItemGetRequest itemget = new ItemGetRequest();
                            itemget.Fields = "pic_url,detail_url,price,title";
                            itemget.NumIid = item.NumIid;
                            ItemGetResponse itemresponse = client.Execute(itemget);
                            string promotionNew = "INSERT INTO Promotion(Pid,Numid,DiscountType,DiscountValue,Startime,Endtime,Promotiontitle,TagID,ParentID,Picurl,Oldprice,Detailurl,GoodTitle)";
                            promotionNew += "VALUES(" + item.PromotionId + "," + item.NumIid + ",'" + type + "','" + goodprice + "','" + gaijiastarttime + "','" + gaijiaovertime + "','" + ptitle + "'," + 1 + ",'" + parentid + "','" + itemresponse.Item.PicUrl + "','" + itemresponse.Item.Price + "','" + itemresponse.Item.DetailUrl + "','" + itemresponse.Item.Title + "')";
                            sdh.ExecuteNonQuery(promotionNew);
                        }
                        p.Clear();
                    }
                }
            }
            catch (Exception)
            {

                errMsg = "活动部分商品添加失败，请检查后重新添加";
            }

            if (errMsg != "")
            {
                context.Response.Write(errMsg);
                context.Response.End();
            }
            else
            {
                context.Response.Write("ok");
                context.Response.End();
            }
        }

        /// <summary>
        /// 添加定向优惠
        /// </summary>
        /// <param name="numid">商品ID</param>
        /// <param name="discountype">折扣类型，有打折DISCOUNT和优惠价PRICE</param>
        /// <param name="discountvalue">折扣值,打折为x.x的百分比值，优惠价直接填价格</param>
        /// <param name="gid">人群ID</param>
        /// <returns></returns>
        private Boolean addPromotion(string promotiontitle,string numid, string discountype, string discountvalue, string sessionkey, string priceovertime,string pricestarttime, out List<Promotion> outpromotion)
        {
            DateTime endtime = DateTime.Parse(priceovertime); //DateTime.Now.AddMinutes(priceovertime);
            DateTime starttime = DateTime.Parse(pricestarttime);
            //et = endtime;
            //st = starttime;
            MarketingPromotionAddRequest req = new MarketingPromotionAddRequest();
            req.NumIids = numid;
            req.DiscountType = discountype;
            req.DiscountValue = discountvalue;
            req.StartDate = starttime;
            req.EndDate = endtime;
            req.PromotionTitle = promotiontitle;
            req.PromotionDesc = "优惠持续到" + endtime.Year + "年" + endtime.Month + "月" + endtime.Day + "日";
            req.TagId = 1;
            MarketingPromotionAddResponse response = client.Execute(req, sessionkey);
            if (response.IsError) { errMsg = response.SubErrMsg; outpromotion = null; return false; }
            outpromotion = response.Promotions;
            return true;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}